<?php

namespace yunj\app\demo\service\form;

use yunj\app\admin\enum\auth\AuthType;
use yunj\app\demo\model\User as UserModel;
use yunj\core\enum\Def;

final class Index {

    /**
     * @var UserModel
     */
    private $userModel;

    /**
     * @return UserModel
     */
    public function getUserModel(): UserModel {
        if (!$this->userModel) $this->setUserModel();
        return $this->userModel;
    }

    /**
     * @param UserModel $userModel
     */
    public function setUserModel(UserModel $userModel = null): void {
        $this->userModel = $userModel ?: (new UserModel());
    }

    private static $instance;

    public static function getInstance() {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Notes: 切换栏
     * Author: Uncle-L
     * Date: 2021/11/13
     * Time: 18:15
     * @return array
     */
    public function tab(): array {
        return ["normal" => "常规", "require" => "必填", "default" => "默认", "readonly" => "只读"];
    }

    /**
     * Notes: 表单字段
     * Author: Uncle-L
     * Date: 2021/11/13
     * Time: 18:16
     * @param $tab
     * @return array
     */
    public function field($tab): array {
        $field = [];
        $tabField = [
            "hidden" => [
                "title" => "隐藏域",
                "type" => "hidden",
            ],
            "markdown" => [
                "title" => "Markdown",
                "type" => "markdown",
//                "default" => "123123"
            ],
            "file_single" => [
                "title" => "单文件上传",
                "type" => "file",
//                "readonly" => true,
//                "default"=>'http://yunjadmintp6.lz.com/upload/file/20240607/2f42c02024d83b71b71e0776e9a6c332/1_1919_客户列表_20240606114625 (1).csv',
                "grid" => [12, 6, 6]
            ],
            "file_multi" => [
                "title" => "多文件上传",
                "type" => "file",
                "multi" => true,
//                "readonly" => true,
//                "default"=>'http://yunjadmintp6.lz.com/upload/file/20240607/2f42c02024d83b71b71e0776e9a6c332/1_1919_客户列表_20240606114625 (1).csv',
                "grid" => [12, 6, 6]
            ],
            "image_single" => [
                "title" => "单图片上传",
                "type" => "image",
//                "readonly" => true,
//                'default' => 'http://yunjadmintp6.lz.com/upload/img/20240607/35774379d3703d40c2690b687a982798.jpg',
                "grid" => [12, 6, 6]
            ],
            "image_multi" => [
                "title" => "多图片上传",
                "type" => "image",
                "multi" => true,
//                "readonly" => true,
//                'default' => 'http://yunjadmintp6.lz.com/upload/img/20240607/35774379d3703d40c2690b687a982798.jpg',
                "grid" => [12, 6, 6]
            ],
            "date" => [
                "title" => "日期",
                "type" => "date",
                "grid" => [12, 3, 3],
                "shortcuts" => [
                    [
                        "text" => "昨天",
                        "value" => "()=>{return yunj.getDaysDateObj(-1);}",
                    ],
                    [
                        "text" => "今天",
                        "value" => "()=>{return new Date();}",
                        //"value" => "2024-08-08",
                        //"value" => "new Date()",
                    ],
                    [
                        "text" => "明天",
                        "value" => "()=>{return yunj.getDaysDateObj(1);}",
                    ],
                    [
                        "text" => "上个月",
                        "value" => "()=>{return yunj.getMonthsTodayDateObj(-1);}",
                    ],
                    [
                        "text" => "下个月",
                        "value" => "()=>{return yunj.getMonthsTodayDateObj(1);}",
                    ],
                ],
            ],
            "date_range" => [
                "title" => "日期范围",
                "type" => "date",
                "range" => true,
                "grid" => [12, 3, 3],
                "shortcuts" => [
                    [
                        "text" => "上周",
                        "value" => "()=>{return [yunj.getLastWeekStartDateObj(),yunj.getLastWeekEndDateObj()];}",
                    ],
                    [
                        "text" => "本周",
                        "value" => "()=>{return [yunj.getCurrWeekStartDateObj(),new Date()];}",
                    ],
                    [
                        "text" => "上月",
                        "value" => "()=>{return [yunj.getMonthsStartDateObj(-1),yunj.getMonthsEndDateObj(-1)];}",
                    ],
                    [
                        "text" => "本月",
                        "value" => "()=>{return [yunj.getCurrMonthStartDateObj(),new Date()];}",
                    ],
                    [
                        "text" => "最近一周",
                        "value" => "()=>{return [yunj.getDaysDateObj(-7),new Date()];}",
                    ],
                    [
                        "text" => "最近一月",
                        "value" => "()=>{return [yunj.getMonthsTodayDateObj(-1),new Date()];}",
                    ],
                    [
                        "text" => "最近三月",
                        "value" => "()=>{return [yunj.getMonthsTodayDateObj(-3),new Date()];}",
                    ]
                ],
            ],
            "datetime" => [
                "title" => "时间日期",
                "type" => "datetime",
                "grid" => [12, 3, 3],
                "shortcuts" => [
                    [
                        "text" => "昨天",
                        "value" => "()=>{return yunj.getDaysDateObj(-1);}",
                    ],
                    [
                        "text" => "今天",
                        "value" => "()=>{return new Date();}",
                    ],
                    [
                        "text" => "明天",
                        "value" => "()=>{return yunj.getDaysDateObj(1);}",
                    ],
                    [
                        "text" => "上个月",
                        "value" => "()=>{return yunj.getMonthsTodayDateObj(-1);}",
                    ],
                    [
                        "text" => "下个月",
                        "value" => "()=>{return yunj.getMonthsTodayDateObj(1);}",
                    ],
                ],
            ],
            "datetime_range" => [
                "title" => "时间日期范围",
                "type" => "datetime",
                "range" => true,
                "grid" => [12, 3, 3],
                "shortcuts" => [
                    [
                        "text" => "上周",
                        "value" => "()=>{return [yunj.getLastWeekStartDateObj(),yunj.getLastWeekEndDateObj()];}",
                    ],
                    [
                        "text" => "本周",
                        "value" => "()=>{return [yunj.getCurrWeekStartDateObj(),new Date()];}",
                    ],
                    [
                        "text" => "上月",
                        "value" => "()=>{return [yunj.getMonthsStartDateObj(-1),yunj.getMonthsEndDateObj(-1)];}",
                    ],
                    [
                        "text" => "本月",
                        "value" => "()=>{return [yunj.getCurrMonthStartDateObj(),new Date()];}",
                    ],
                    [
                        "text" => "最近一周",
                        "value" => "()=>{return [yunj.getDaysDateObj(-7),new Date()];}",
                    ],
                    [
                        "text" => "最近一月",
                        "value" => "()=>{return [yunj.getMonthsTodayDateObj(-1),new Date()];}",
                    ],
                    [
                        "text" => "最近三月",
                        "value" => "()=>{return [yunj.getMonthsTodayDateObj(-3),new Date()];}",
                    ]
                ],
            ],
            "year" => [
                "title" => "年份",
                "type" => "year",
                "grid" => [12, 3, 3],
                "shortcuts" => [
                    [
                        "text" => "去年",
                        "value" => "()=>{return yunj.getYearsDateObj(-1);}",
                    ],
                    [
                        "text" => "今年",
                        "value" => "()=>{return new Date();}",
                    ],
                    [
                        "text" => "明年",
                        "value" => "()=>{return yunj.getYearsDateObj(1);}",
                    ],
                    [
                        "text" => "三年前",
                        "value" => "()=>{return yunj.getYearsDateObj(-3);}",
                    ],
                    [
                        "text" => "三年后",
                        "value" => "()=>{return yunj.getYearsDateObj(3);}",
                    ],
                ],
            ],
            "year_range" => [
                "title" => "年份范围",
                "type" => "year",
                "range" => true,
                "grid" => [12, 3, 3],
                "shortcuts" => [
                    [
                        "text" => "去年",
                        "value" => "()=>{return [yunj.getYearsDateObj(-1),new Date()];}",
                    ],
                    [
                        "text" => "明年",
                        "value" => "()=>{return [new Date(),yunj.getYearsDateObj(1)];}",
                    ],
                    [
                        "text" => "近三年",
                        "value" => "()=>{return [yunj.getYearsDateObj(-3),new Date()];}",
                    ],
                ],
            ],
            "yearMonth" => [
                "title" => "年月",
                "type" => "yearMonth",
                "grid" => [12, 3, 3],
                "shortcuts" => [
                    [
                        "text" => "上个月",
                        "value" => "()=>{return yunj.getMonthsYearMonthDateObj(-1);}",
                    ],
                    [
                        "text" => "下个月",
                        "value" => "()=>{return yunj.getMonthsYearMonthDateObj(1);}",
                    ],
                    [
                        "text" => "去年本月",
                        "value" => "()=>{return yunj.getMonthsYearMonthDateObj(-12);}",
                    ],
                ],
            ],
            "yearMonth_range" => [
                "title" => "年月范围",
                "type" => "yearMonth",
                "range" => true,
                "grid" => [12, 3, 3],
                "shortcuts" => [
                    [
                        "text" => "去年",
                        "value" => "()=>{return [yunj.getYearsStartDateObj(-1),yunj.getYearsEndDateObj(-1)];}",
                    ],
                    [
                        "text" => "明年",
                        "value" => "()=>{return [yunj.getYearsStartDateObj(1),yunj.getYearsEndDateObj(1)];}",
                    ],
                    [
                        "text" => "近三年",
                        "value" => "()=>{return [yunj.getMonthsYearMonthDateObj(-36),new Date()];}",
                        //"value" => ["2024-01","2024-02"],
                    ],
                ],
            ],
            "time" => [
                "title" => "时间",
                "type" => "time",
                "grid" => [12, 3, 3],
                "shortcuts" => [
                    [
                        "text" => "09:00:00",
                        //"value" => "()=>{return yunj.getTimeDateObj(9);}",
                        "value" => "09:00:00",
                    ],
                    [
                        "text" => "12:00:00",
                        "value" => "()=>{return yunj.getTimeDateObj(12);}",
                    ],
                    [
                        "text" => "17:00:00",
                        "value" => "()=>{return yunj.getTimeDateObj(17);}",
                    ],
                ],
            ],
            "time_range" => [
                "title" => "时间范围",
                "type" => "time",
                "range" => true,
                "grid" => [12, 3, 3],
                "shortcuts" => [
                    [
                        "text" => "9-12点",
                        "value" => "()=>{return [yunj.getTimeDateObj(9),yunj.getTimeDateObj(12)];}",
                    ],
                    [
                        "text" => "13-17点",
                        "value" => "()=>{return [yunj.getTimeDateObj(13),yunj.getTimeDateObj(17)];}",
                    ],
                ]
            ],
            "text" => [
                "title" => "单行文本框",
                "type" => "text",
                "verify" => "max:10",
                "grid" => [12, 6, 6],
            ],
            "textarea" => [
                "title" => "多行文本框",
                "type" => "textarea",
                "verify" => "max:100",
            ],
            "password" => [
                "title" => "密码框",
                "type" => "password",
                "grid" => [12, 6, 6],
            ],
            "dropdownSearchOptionsUrl" => [
                "title" => "下拉搜索（可选数据请求地址）",
                "type" => "dropdownSearch",
                "options" => build_url('yunjDemoFormBuilderDropdownSearchOptions', ['originLocation' => request()->param('originLocation', AuthType::SIDEBAR_MENU)]),
                "grid" => [12, 6, 6]
            ],
            "dropdownSearchOptionsArr" => [
                "title" => "下拉搜索（可选数据数组）",
                "type" => "dropdownSearch",
                "options" => [
                    ['id' => 1, 'name' => '小王'],
                    ['id' => 2, 'name' => '小李'],
                    ['id' => 3, 'name' => '小张'],
                    ['id' => 4, 'name' => '小梁'],
                    ['id' => 5, 'name' => '小汤'],
                ],
                "grid" => [12, 6, 6]
            ],
            "dropdownSearchSingleOptionsArr" => [
                "title" => "下拉搜索（单选-可选数据数组）",
                "type" => "dropdownSearch",
                "multi" => false,
                "options" => [
                    ['id' => 1, 'name' => '小王'],
                    ['id' => 2, 'name' => '小李'],
                    ['id' => 3, 'name' => '小张'],
                    ['id' => 4, 'name' => '小梁'],
                    ['id' => 5, 'name' => '小汤'],
                ],
                "grid" => [12, 6, 6]
            ],
            "tree" => [
                "title" => "树（末级可选）",
                "type" => "tree",
                "maxHeight" => 'auto',
                "nodes" => [
                    ["id" => 1, "pid" => 0, "name" => "节点一"],
                    ["id" => 2, "pid" => 0, "name" => "节点二"],
                    ["id" => 3, "pid" => 1, "name" => "节点三"],
                    ["id" => 4, "pid" => 3, "name" => "节点四", "checked" => true, "readonly" => true],
                    ["id" => 5, "pid" => 2, "name" => "节点五"],
                    ["id" => 6, "pid" => 2, "name" => "节点六"],
                ],
                "grid" => [12, 6, 6]
            ],
            "tree_allOptional" => [
                "title" => "树（所有可选）",
                "type" => "tree",
                "maxHeight" => 'auto',
                "allOptional" => true,
                "nodes" => [
                    ["id" => 1, "pid" => 0, "name" => "节点一"],
                    ["id" => 2, "pid" => 0, "name" => "节点二"],
                    ["id" => 3, "pid" => 1, "name" => "节点三"],
                    ["id" => 4, "pid" => 3, "name" => "节点四", "checked" => true, "readonly" => true],
                    ["id" => 5, "pid" => 2, "name" => "节点五"],
                    ["id" => 6, "pid" => 2, "name" => "节点六"],
                ],
                "grid" => [12, 6, 6]
            ],
            "tree_edit" => [
                "title" => "树（编辑）",
                "type" => "tree",
                "mode" => "edit",
                "dragSort" => "level",
                "options" => [
                    [
                        "type" => "openTab",
                        "event" => "edit",
                        "url" => "/edit",
                        "title" => "编辑",
                        "icon" => "layui-icon-edit",
                        "confirmText" => "确认这么做？",
                    ],
                    "rename", "remove"
                ],
                // 默认值
                "default" => [
                    ["id" => 1, "pid" => 0, "name" => "衣服", "readonly" => true],
                    ["id" => 2, "pid" => 1, "name" => "衬衣"],
                    ["id" => 3, "pid" => 1, "name" => "短袖", "drag" => false],
                    ["id" => 4, "pid" => 0, "name" => "帽子"],
                    ["id" => 5, "pid" => 4, "name" => "遮阳帽"],
                    ["id" => 6, "pid" => 0, "name" => "手套"]
                ],
                "grid" => [12, 6, 6]
            ],
            "table" => [
                "title" => "表格",
                "type" => "table",
//                "readonly" => true,
                "maxHeight" => "400",
                "cols" => [['title' => '姓名', 'field' => 'name', 'verify' => 'require'], ['title' => '年龄', 'field' => 'age']],
            ],
            "txt" => [
                "type" => "txt",
                "desc" => "提示信息  这是一个温馨提示哦！",
            ],
            "line" => [
                "title" => "我是分割线",
                "type" => "line",
            ],
            "icon" => [
                "title" => "图标",
                "type" => "icon",
                "grid" => [12, 6, 6],
            ],
            "editor" => [
                "title" => "富文本",
                "type" => "editor",
            ],
            "select" => [
                "title" => "下拉选框",
                "type" => "select",
                "options" => ["option1" => "选项一", "option2" => "选项二"],
                "grid" => [12, 6, 6],
            ],
            "radio" => [
                "title" => "单选框",
                "type" => "radio",
                "options" => ["option1" => "选项一", "option2" => "选项二"],
                "grid" => [12, 6, 6],
            ],
            "checkbox" => [
                "title" => "复选框",
                "type" => "checkbox",
                "options" => ["option1" => "选项一", "option2" => "选项二"],
                "grid" => [12, 6, 6],
            ],
            "switch" => [
                "title" => "开关",
                "type" => "switch",
                "text" => "开|关",
                "grid" => [12, 6, 6],
            ],
            "color" => [
                "title" => "取色器",
                "type" => "color",
                "grid" => [12, 3, 3],
            ],
            "area" => [
                "title" => "地区联动",
                "type" => "area",
                "grid" => [12, 3, 3],
            ],
        ];
        foreach ($tabField as $k => $v) {
            switch ($tab) {
                case "require":
                    if (isset($v['title'])) $v['title'] .= '（必填）';
                    $v["verify"] = "require";
                    $this->setFieldDefault($v);
                    break;
                case "default":
                    if (isset($v['title'])) $v['title'] .= '（默认）';
                    $this->setFieldDefault($v);
                    break;
                case "readonly":
                    if (isset($v['title'])) $v['title'] .= '（只读）';
                    $this->setFieldDefault($v);
                    $v["readonly"] = true;
                    break;
            }
            $field["{$tab}_{$k}"] = $v;
        }
        return $field;
    }

    private function setFieldDefault(array &$field) {
        $type = isset($field["type"]) ? $field["type"] : "text";
        if (in_array($type, ["select", "radio", "checkbox"])) {
            $default = "option1";
        } elseif ($type == 'icon') {
            $default = "yunj-icon-sub";
        } elseif ($type == 'date') {
            $default = Def::PROJECT_START_DATE;
            if (($range = $field['range'] ?? false) !== false)
                $default = ["start" => $default, "end" => date('Y-m-d')];
        } elseif ($type == 'datetime') {
            $default = Def::PROJECT_START_DATETIME;
            if (($range = $field['range'] ?? false) !== false)
                $default = ["start" => $default, "end" => date('Y-m-d H:i:s')];
        } elseif ($type == 'year') {
            $default = Def::PROJECT_START_YEAR;
            if (($range = $field['range'] ?? false) !== false)
                $default = ["start" => $default, "end" => date('Y')];
        } elseif ($type == 'yearMonth') {
            $default = Def::PROJECT_START_YEAR_MONTH;
            if (($range = $field['range'] ?? false) !== false)
                $default = ["start" => $default, "end" => date('Y-m')];
        } elseif ($type == 'time') {
            $default = '00:00:00';
            if (($range = $field['range'] ?? false) !== false)
                $default = ["start" => $default, "end" => date('H:i:s')];
        } elseif ($type == 'image') {
            $default = !empty($field['multi']) ? [request_domain() . Def::IMG_URI, request_domain() . Def::IMG_URI] : request_domain() . Def::IMG_URI;
        } elseif ($type == 'file') {
            $default = !empty($field['multi']) ? [request_domain() . Def::TEST_FILE_URL, request_domain() . Def::TEST_FILE_URL] : request_domain() . Def::TEST_FILE_URL;
        } elseif ($type == 'area') {
            $default = ['province' => '110000', 'city' => '110100', 'district' => '110101'];
        } elseif ($type == 'dropdownSearch') {
            if (is_string($field['options'])) {
                static $lastId;
                $lastId = $lastId ?? $this->getUserModel()->getFieldValue('id', [['create_time' => 'desc']]);
                $default = $lastId;
            } else {
                $default = 1;
            }
        } elseif ($type == 'tree') {
            $default = [1, 3, 5];
            if (($field["mode"] ?? '') == 'edit') {
                $default = $field["default"];
            }
        } elseif ($type == 'table') {
            $default = [['name' => '小王', 'age' => 18]];
        } else {
            $default = "初始默认值";
        }
        $field["default"] = $default;
    }

    public function dropdownSearchOptions(array $param = []): array {
        $param = $param ?: input('get.');
        $ids = filter_sql($param['ids']);
        $keywords = filter_sql($param['keywords']);

        $where = [];
        if ($ids) $where[] = ['id', 'in', $ids];
        if ($keywords) $where[] = ['name', 'like', "%{$keywords}%"];
        $field = ['id', 'name'];
        $items = $this->getUserModel()->getOwnRowsToArray($where, $field, ["id" => "desc"], 0, 20);
        return $items;
    }

}